package com.taiji.dicom4cloud.common.security.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.taiji.dicom4cloud.common.core.constrant.constant.SecurityConstants;
import com.taiji.dicom4cloud.common.model.entity.SysUser;
import com.taiji.dicom4cloud.common.security.model.CommonUserDetails;
import lombok.experimental.UtilityClass;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/20
 **/
@UtilityClass
public class SecurityUtils {

    public static SysUser getUser(){
        if(ObjectUtil.isNull(SecurityContextHolder.getContext().getAuthentication())){
            return null;
        }
        if(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken){
            return null;
        }
        SysUser user = new SysUser();
        CommonUserDetails userDetails = (CommonUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        BeanUtil.copyProperties(userDetails,user);
        return user;
    }
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
    /**
     * 获取用户角色信息
     * @return 角色集合
     */
    public  List<Integer> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Integer> roleIds = new ArrayList<>();
        authorities.stream().filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
                .forEach(granted -> {
                    String id = StrUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
                    roleIds.add(Integer.parseInt(id));
                });
        return roleIds;
    }
}
